from db import pg, namedata
from util import unixtime as epoch
from random import random
from log import logging
from pdb import set_trace
import conf

def getId(request):
  if request.session.has_key("user_id"):
    uid = request.session["user_id"]
    assert isinstance(uid,int) or isinstance(uid,long)
    
  else:
    profile = login(request)
    uid = profile["id"]
  return uid

def getById(uid):
  pg.cursor.execute("SELECT id,name,location,games_played,games_won FROM users WHERE id = %i"%uid)
  result = pg.cursor.fetchone()
  if result: result = namedata.single(result,("id","name","location","gamesPlayed","gamesWon"))
  return result

def login(request):
  if not request.session.get("user_id"):
    profile = register()
    request.session["user_id"] = profile["id"]
  else:
    pg.cursor.execute("SELECT id,name,location,games_played,games_won FROM users WHERE id = %i"%request.session["user_id"])
    result = pg.cursor.fetchone()
    
    if not result:
      request.session.pop("user_id")
      return login(request)
    
    profile = namedata.single(result,("id","name","location","games_played","games_won"))
    
  return profile

def register():
  username = "~guest_%s"%int(random()*1000000000)
  pg.cursor.execute("INSERT INTO users(name,location,last_move_epoch) VALUES ('%(name)s','%(location)s',%(epoch)i)"%{ "name":username, "location":"United States", "epoch":epoch() })
  pg.connection.commit()
  logging.info("getting id of last insert..")
  pg.cursor.execute("SELECT CURRVAL('users_id_seq')")
  uid = pg.cursor.fetchone()[0]
  
  return { "id":uid, "name":username, "location":"United States", "games_played":0, "games_won":0 }

def update(userId):
  pg.cursor.execute("UPDATE users SET last_move_epoch = %i WHERE id = %i"%( epoch(), userId ))
  pg.connection.commit()
  
def updateProfile(userId,name,location):
  pg.cursor.execute("SELECT id FROM users WHERE name = '%s' AND last_move_epoch>%i"%(name,epoch()-conf.CHESS_SERVER['timeout']))
  result = pg.cursor.fetchone()
  if result and result[0]!=userId:
    name = '%s_%i'%(name,int(random()*1000))
  pg.cursor.execute("UPDATE users SET name = '%s', location='%s', last_move_epoch = %i WHERE id = %i"%(name,location,epoch(),userId))
  pg.connection.commit()
